﻿using Microsoft.EntityFrameworkCore;
using Mojito.Data;
using Mojito.Data.Entities;
using Mojito.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mojito.Services
{
    public class SysAccountService : AppServiceBase
    {
        /// <summary>
        ///  用户注册
        /// </summary>
        /// <param name="credential">登录凭据</param>
        /// <param name="password">口令明文</param>
        /// <param name="phone">手机号码</param>
        /// <returns></returns>
        public async Task<int> Register(string credential, string password, string phone)
        {
            if (await Context.Sys_Account.AnyAsync(d => d.Username == credential || d.TelPhone == phone))
            {
                throw new ApplicationException("用户名或手机号码被占用");
            }

            var newAccount = new Sys_Account
            {
                Id = Guid.NewGuid().ToString("N"),
                Username = credential,
                Password = StringUtil.MD5Encrypt(password),
                TelPhone = phone,
                IsActive = true,
                TryCount = 0,
                Name = "新用户"
            };

            await Context.Sys_Account.AddAsync(newAccount);
            return await Context.SaveChangesAsync();
        }


        /// <summary>
        ///  用户登录判定
        /// </summary>
        /// <param name="credential">登录凭据</param>
        /// <param name="password">口令明文</param>
        /// <returns></returns>
        public Sys_Account Login(string credential, string password)
        {
            // 用户名/手机号验证
            var user = Context.Sys_Account.FirstOrDefault(d => d.TelPhone == credential || d.Username == credential);

            if (user == null)
            {
                throw new ApplicationException("账户或密码错误");
            }

            // 账户状态验证
            if (!user.IsActive)
            {
                throw new ApplicationException("该账户已被锁定, 请联系管理员");
            }

            // 密码验证
            if (user.Password != StringUtil.MD5Encrypt(password))
            {
                user.IsActive = !(++user.TryCount >= 5);
                Context.Update(user);
                throw new ApplicationException($"密码错误, 尝试次数过多将会锁定账户");
            }

            user.TryCount = 0;
            Context.Update(user);

            return user;
        }

        /// <summary>
        ///  根据id获取用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Sys_Account> Get(string id)
        {
            return await Context.FindAsync<Sys_Account>(id);
        }     
        
        /// <summary>
        ///  根据 用户名/手机号/Email 获取用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IList<Sys_Account>> GetByUsername(string username)
        {
            var userList = Context.Sys_Account.Where(d =>
                d.Username.Contains(username) ||
                d.TelPhone.Contains(username) ||
                d.Email.Contains(username)
            ).ToList();
            return userList;
        }

        /// <summary>
        ///  更新用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //public virtual void Update(SysAccountVO input)
        //{
        //    var user = _SysAccountRepository.GetEntity(input.Id);

        //    if (user == null)
        //    {
        //        user = new Sys_Account
        //        {
        //            Name = input.Name,
        //            Username = input.Username,
        //            TelPhone = input.TelPhone,
        //            Email = input.Email,
        //            IsAdmin = false,
        //            IsActive = input.IsActive
        //        };
        //        _SysAccountRepository.Insert(user);
        //    }
        //    else
        //    {
        //        user.Name = input.Name;
        //        user.Username = input.Username;
        //        user.TelPhone = input.TelPhone;
        //        user.Email = input.Email;
        //        user.IsActive = input.IsActive;
        //        _SysAccountRepository.Update(user);
        //    }

        //    _SysAccountRoleRepository.Delete(d => d.AccountId == input.Id);
        //    var accountRole = input.Roles
        //        .Select(s => new Sys_AccountRole
        //        {
        //            AccountId = input.Id,
        //            RoleId = s
        //        });
        //    _SysAccountRoleRepository.Insert(accountRole);
        //}

        /// <summary>
        ///  更新用户的密码
        /// </summary>
        /// <param name="userid">账号id</param>
        /// <param name="input">更新内容</param>
        /// <returns></returns>
        //public int UpdatePassword(int userid, UpdatePasswordInput input)
        //{
        //    var user = _SysAccountRepository.GetEntity(userid);
        //    var password = StringUtil.MD5Encrypt(input.Password);
        //    if (user == null)
        //        throw new ApplicationException("找不到该账号信息");
        //    if (password != user.Password)
        //        throw new ApplicationException("原密码错误");
        //    if (input.NewPassword != input.ConfirmPassword)
        //        throw new ApplicationException("两次密码不相同");
        //    user.Password = StringUtil.MD5Encrypt(input.NewPassword);
        //    return _SysAccountRepository.Update(user);
        //}
    }
}
